<template>
  <view>
    <swiper class="m-tiktok-video-swiper" circular @change="swiperChange" :current="state.current" :vertical="true"
            duration="300">
      <swiper-item v-for="(item, index) in state.displaySwiperList" :key="index">
        <view class="swiper-item" @click="handleClick">
          <video class="m-tiktok-video-player" :src="item.videoSrc" :id="`video__${index}`" :controls="controls"
                 :show-center-play-btn="controls" object-fit="cover" :autoplay="false" :loop="loop"
                 :custom-cache="false" @ended="ended" @controlstoggle="controlstoggle" @play="onPlay"
                 @error="error" @loadedmetadata="loadVideoData($event, item)"
                 v-if="index === 0 || !state.isFirstLoad"></video>
          <view class="m-tiktok-video-play-btn" v-if="!controls && state.displayIndex === index"
                @click="togglePlay">
            <text class="m-tiktok-video-iconfont video-icon"
                  :class="{ active: !state.isPlaying }">&#xe607;</text>
          </view>
          <image v-if="item.tvImage && state.displayIndex !== index" :src="item.tvImage" class="m-tiktok-video-poster" mode="aspectFit"></image>
          <slot :item="item"></slot>
          <view class="watchGo" style="" @click="goDetails(item)">
            <view>正在观看：{{ item.tvName }}</view>
            <view>点击观看全集</view>
          </view>
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
// import { getMedialink } from '@/app/api/video';
import {Api} from "../../service/api";
import {gotoPage} from "../../utils/common";

export default {
  data() {
    return {
      videoList: [], // 视频列表
      loop: true, // 是否循环播放一个视频
      controls: false, // 显示原生控制栏
      autoplay: true, // 是否自动播放
      autoChange: false, // 是否自动滚动播放
      loadMoreOffsetCount: 2, // 滚动加载阈值（即播放到剩余多少个之后触发加载更多
      autoObjectFit: true, // 是否自动自适应平铺模式
      state: {
        originList: [], // 源数据
        displaySwiperList: [], // swiper需要的数据
        displayIndex: 0, // 用于显示swiper的真正的下标数值只有：0，1，2。
        originIndex: 0, // 记录源数据的下标
        current: 0,
        oid: 0,
        videoContexts: [],
        isFirstLoad: true,
        isPlaying: false
      },
      firsEntry: false,
      loadTimer: null,
      pageObj:{
        pageNo: 0,
        pageSize: 10,
        status: "loading"
      }
    };
  },
  async onLoad(){
    await this.getList()
    if (this.state.isFirstLoad || !this.state.videoContexts?.length) {
      this.initSwiperData();
      this.initVideoContexts();
    }
  },
  // watch: {
  //   videoList(old,newV){
  //     console.log('videoList',old,newV)
  //     if(this.videoList?.length){
  //       uni.showLoading({
  //         title: '加载中...',
  //         mask: true // 是否显示透明蒙层，防止触摸穿透
  //       });
  //       // this.videoList.forEach(async (row, index) => {
  //       //   row.src = row.mp4_url;
  //       // });
  //       uni.hideLoading();
  //       this.state.originList = this.videoList;
  //       if (this.state.isFirstLoad || !this.state.videoContexts?.length) {
  //         this.initSwiperData();
  //         this.initVideoContexts();
  //       }
  //     }
  //   }
  // },
  onUnload(){
    clearTimeout(this.loadTimer);
  },
  methods: {
    async getList(){
      if(this.pageObj.status === 'nomore') return
      this.pageObj.status = 'loading'
      uni.showLoading({
        title: '加载中...',
        mask: true // 是否显示透明蒙层，防止触摸穿透
      });
      let res = await Api.getWatchPage({
        pageNo: ++ this.pageObj.pageNo,
        pageSize: this.pageObj.pageSize
      })
      this.videoList = this.videoList.concat(res.data.list)
      if(this.videoList.length < res.data.total)  this.pageObj.status = 'loadmore'
      else this.pageObj.status = 'nomore'
      this.state.originList = this.videoList
      uni.hideLoading();
    },
    onPlay(e){
      this.state.isPlaying = true;
      this.initFirstLoad();
      // this.$emit('play', e);
    },
    error(e){
      console.log(e)
    },
    initVideoContexts(){
      this.state.videoContexts = [uni.createVideoContext('video__0', this), uni.createVideoContext('video__1', this), uni.createVideoContext('video__2', this)];
    },
    handleClick(){
      // this.$emit('click', e);
    },
    ended() {
      // 自动切换下一个视频
      if (this.autoChange) {
        if (this.state.displayIndex < 2) {
          this.state.current = this.state.displayIndex + 1;
        } else {
          this.state.current = 0;
        }
      }
      // this.$emit('ended');
    },
    goDetails(row) {
      const video = uni.createVideoContext(`video__${this.state.displayIndex}`, this);
      video.pause();
      this.state.isPlaying = false;
      gotoPage(`/pages/player/player?tt_album_id=${row.albumId}&tt_episode_id=0&tvId=${row.tvId}`)
    },
    /**
     * 初始一个显示的swiper数据
     * @originIndex  从源数据的哪个开始显示默认0，如从其他页面跳转进来，要显示第n个，这个参数就是他的下标
     */
    initSwiperData(originIndex = this.state.originIndex) {
      const originListLength = this.state.originList.length; // 源数据长度
      const displayList = [];
      displayList[this.state.displayIndex] = this.state.originList[originIndex];
      displayList[this.state.displayIndex - 1 === -1 ? 2 : this.state.displayIndex - 1] = this.state.originList[originIndex - 1 === -1 ? originListLength - 1 : originIndex - 1];
      displayList[this.state.displayIndex + 1 === 3 ? 0 : this.state.displayIndex + 1] = this.state.originList[originIndex + 1 === originListLength ? 0 : originIndex + 1];

      // 未开发完
      // displayList.forEach(async (row, index) => {
      // 	const res = await getMedialink({ media_id: row.media_id })
      // 	row.src = res.data.media_info.mp4_url
      // })

      this.firsEntry = true;
      this.state.displaySwiperList = displayList;
      if (this.state.oid >= this.state.originList.length) {
        this.state.oid = 0;
      }
      if (this.state.oid < 0) {
        this.state.oid = this.state.originList.length - 1;
      }
      // 暂停所有视频
      this.state.videoContexts.map((item) => item?.stop());
      setTimeout(() => {
        // 当前视频
        if (this.autoplay) {
          uni.createVideoContext(`video__${this.state.displayIndex}`, this).play();
        }
      }, 500);
      // 数据改变
      // this.$emit('change', {
      //   index: originIndex,
      //   detail: this.state.originList[originIndex]
      // });
      // 赋值
      this.state.originIndex = originIndex;
      // 加载更多
      const pCount = this.state.originList.length - this.loadMoreOffsetCount;
      if (originIndex === pCount) {
        this.getList()
        // this.$emit('loadMore');
      }
    },
    /**
     * swiper滑动时候
     */
    swiperChange(event) {
      const { current } = event.detail;
      this.state.isFirstLoad = false;
      const originListLength = this.state.originList.length; // 源数据长度
      // 向后滚动
      if (this.state.displayIndex - current === 2 || this.state.displayIndex - current === -1) {
        this.state.originIndex = this.state.originIndex + 1 === originListLength ? 0 : this.state.originIndex + 1;
        this.state.displayIndex = this.state.displayIndex + 1 === 3 ? 0 : this.state.displayIndex + 1;
        this.state.oid = this.state.originIndex - 1;
        this.initSwiperData(this.state.originIndex);
      }
      // 如果两者的差为-2或者1则是向前滑动
      else if (this.state.displayIndex - current === -2 || this.state.displayIndex - current === 1) {
        this.state.originIndex = this.state.originIndex - 1 === -1 ? originListLength - 1 : this.state.originIndex - 1;
        this.state.displayIndex = this.state.displayIndex - 1 === -1 ? 2 : this.state.displayIndex - 1;
        this.state.oid = this.state.originIndex + 1;
        this.initSwiperData(this.state.originIndex);
      }
    },
    controlstoggle(e) {
      // this.$emit('controlstoggle', e);
    },
    togglePlay() {
      const video = uni.createVideoContext(`video__${this.state.displayIndex}`, this);
      if (this.state.isPlaying) {
        video.pause();
        this.state.isPlaying = false;
      } else {
        video.play();
        this.state.isPlaying = true;
      }
    },
    playSeeked(value) {
      const video = uni.createVideoContext(`video__${this.state.displayIndex}`, this);
      video.seek(value);
    },
    initFirstLoad() {
      if (this.state.isFirstLoad) {
        // 为了首次只加载一条视频（提高首次加载性能），延迟加载后续视频
        this.loadTimer = setTimeout(() => {
          this.state.isFirstLoad = false;
          clearTimeout(loadTimer);
        }, 5000);
      }
    },
    /**
     * 视频源数据加载时触发
     * @param $event
     * @param item
     */
    loadVideoData($event, item) {
      // 如果存在过不修改
      if (item.objectFit) {
        return;
      }
      if (!this.autoObjectFit) {
        return;
      }
      // 自动计算设置视频平铺模式,
      if ($event.detail.width < $event.detail.height) {
        // 竖屏全覆盖平铺
        item.objectFit = 'cover';
      } else {
        // 横屏，居中
        item.objectFit = 'contain';
      }
    },

  }
}

// const emits = defineEmits(['play', 'error', 'loadMore', 'change', 'controlstoggle', 'click', 'ended']);

// defineExpose({
//   initSwiperData,
//   togglePlay,
//   playSeeked
// });
</script>

<style lang="scss">
@font-face {
  font-family: 'm-tiktok-play-icon';
  src: url(data:font/woff2;charset=utf-8;base64,d09GMgABAAAAAAJ0AA0AAAAABlgAAAIiAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP0ZGVE0cGh4GYACCQhEICkhaCwoAATYCJAMQBCAFhQIHLxt4BcieBXbLR4jiyygbC491Mg0vz9JsPPz/ft/2ufeMmCQP9fXfRhxvMKHjkcSsTkqWplJJqpFFfn79mr4NG5fvwujI+EPeZCbudGJcy6oVklRVp8IAdgMJUqD853ceuhm3iSafWxNoC0bbskAmUGABTlrDAgwsC+xJ3/SJf3DecLgpCpyFgDcXlRJ8uiufSVcHBjENilBVIVGQKS50UZ6U1+ApeD7+6kcvRVcl2fZub1Q8/BfJG9VHbUp9J0UAYBWhomIRgUZWYFHOKkgp+FFsyVvmRkB0E4AooAg/DwF/49FSQIJeBMbBDIAEQIzfDW+OPVHX48vXUy26fUwfJnN0+tW5bLx3+dz5fHT61rQEIBDc77r579ZI8793IDWgftfb8/q83gC9Cggqvex6gvqcDoBMGojkOvpX4wgU9OtHC2DcOwgwoYpA6LWDQNHjDgJVr8cCpF7PBOgy4JUA3Xq9BYF+29EgMGAiLlSRfVgDlgyjlmQx7JSsRgVQYkeyy7RLstuoF7Lfid+qAWtxbiWmkbDEVgmyA2hRBHx6jOEomxtSuCEvAg5k/U4c0Bh2XJIYfiwLaz88BE9oYgkrKPS0dWGtk7/X7rqFOsU+TZzFM4k9Qx9jOkEXC3iErR+f0LhcASEUC9g0CtaGY3Jrsjf6zPrqiLsTyi1RpN9z3wPOMRaa6+jQAzbblCgVWLpySeZmOVzvLw8uOfSjoLSEEiV7Yg==) format('woff2');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}

.m-tiktok-video-iconfont {
  font-family: m-tiktok-play-icon;
}

.m-tiktok-video-swiper,
.m-tiktok-video-player {
  width: 100%;
  height: calc(100vh);
  background-color: #000;
}

.m-tiktok-video-swiper {
  .swiper-item {
    position: relative;
  }

  .m-tiktok-video-poster {
    background-color: #000;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  .m-tiktok-video-play-btn {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    display: flex;
    align-items: center;
    justify-content: center;

    .video-icon {
      font-size: 50px;
      display: block;
      color: rgba(255, 255, 255, 0.8);
      opacity: 0;

      &.active {
        opacity: 1;
      }
    }
  }
}

.watchGo {
  width: calc(100% - 80rpx);
  height: 80rpx;
  position: fixed;
  bottom: 0rpx;
  left: 0;
  color: #ffffff;
  font-size: 24rpx;
  line-height: 80rpx;
  background: rgba(0, 0, 0, 0.8);
  padding: 8rpx 40rpx;
  display: flex;
  justify-content: space-between;
  z-index: 2;
}
</style>